package com.sjx.onelinecord.socket

import android.annotation.SuppressLint
import android.content.Intent
import android.os.Bundle
import android.os.Handler
import android.os.Message
import android.os.SystemClock
import android.text.TextUtils
import android.view.View
import android.widget.Button
import android.widget.EditText
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import com.sjx.onelinecord.R
import com.sjx.onelinecord.socket.TCPClientAty
import java.io.*
import java.net.Socket
import java.text.SimpleDateFormat
import java.util.*

class TCPClientAty : AppCompatActivity(), View.OnClickListener {
    private var mSendButton: Button? = null
    private var mMessageTextView: TextView? = null
    private var mMessageEditText: EditText? = null
    private var mPrintWriter: PrintWriter? = null
    private var mClientSocket: Socket? = null

    @SuppressLint("HandlerLeak")
    private val handler: Handler = object : Handler() {
        @SuppressLint("SetTextI18n")
        override fun handleMessage(msg: Message) {
            when (msg.what) {
                MESSAGE_RECEIVE_NEW_MSG -> {
                    mMessageTextView!!.text = mMessageTextView!!.text
                            .toString() + msg.obj as String
                }
                MESSAGE_SOCKET_CONNECTED -> {
                    mSendButton!!.isEnabled = true
                }
                else -> {
                }
            }
            super.handleMessage(msg)
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_tcpclient_aty)
        mMessageTextView = findViewById(R.id.mTvMessage)
        mSendButton = findViewById<View>(R.id.mBtnSend) as Button
        mMessageEditText = findViewById<View>(R.id.mEtMessage) as EditText
        mSendButton!!.setOnClickListener(this)
        val service = Intent(this, TCPServerService::class.java)
        startActivity(service)
        object : Thread() {
            override fun run() {
                super.run()
                try {
                    connectTCPServer()
                } catch (e: IOException) {
                    e.printStackTrace()
                }
            }
        }.start()
    }

    @SuppressLint("SetTextI18n")
    override fun onClick(v: View) {
        if (v === mSendButton) {
            val msg = mMessageEditText!!.text.toString()
            if (!TextUtils.isEmpty(msg) && mPrintWriter != null) {
                mPrintWriter!!.println(msg)
                mMessageEditText!!.setText("")
                val time = formatDateTime(System.currentTimeMillis())
                val showedMsg = "self$time:$msg\n"
                mMessageTextView!!.text = mMessageTextView!!.text.toString() + showedMsg
            }
        }
    }

    @SuppressLint("SimpleDateFormat")
    private fun formatDateTime(time: Long): String {
        return SimpleDateFormat("(HH:mm:ss").format(Date(time))
    }

    override fun onDestroy() {
        super.onDestroy()
        if (mClientSocket != null) {
            try {
                mClientSocket!!.shutdownInput()
                mClientSocket!!.close()
            } catch (e: IOException) {
                e.printStackTrace()
            }
        }
    }

    @Throws(IOException::class)
    private fun connectTCPServer() {
        var socket: Socket? = null
        while (socket == null) {
            socket = Socket("localhost", 8688)
            mClientSocket = socket
            mPrintWriter = PrintWriter(BufferedWriter(
                    OutputStreamWriter(socket.getOutputStream())
            ), true)
            handler.sendEmptyMessage(MESSAGE_SOCKET_CONNECTED)
            println("connect server success")
            SystemClock.sleep(1000)
            println("connect tcp server failed,retry...")
        }
        //接受服务器端信息
        val br = BufferedReader(InputStreamReader(
                socket.getInputStream()
        ))
        while (!this@TCPClientAty.isFinishing) {
            val msg = br.readLine()
            println("receive:$msg")
            if (msg != null) {
                val time = formatDateTime(System.currentTimeMillis())
                val showedMsg = "servertime:$msg\n"
                handler.obtainMessage(MESSAGE_RECEIVE_NEW_MSG, showedMsg).sendToTarget()
            }
        }
        println("quit...")
        mPrintWriter!!.close()
        br.close()
        socket.close()
    }

    companion object {
        private const val MESSAGE_RECEIVE_NEW_MSG = 1
        private const val MESSAGE_SOCKET_CONNECTED = 2
    }
}